package com.iptv.devices.controller;

import com.iptv.common.annotation.Log;
import com.iptv.common.core.controller.BaseController;
import com.iptv.common.core.domain.AjaxResult;
import com.iptv.common.core.page.TableDataInfo;
import com.iptv.common.enums.BusinessType;
import com.iptv.common.utils.RegistrationTokenUtils;
import com.iptv.devices.domain.LiveDevices;
import com.iptv.devices.domain.dto.DeviceExternallyAddedDTO;
import com.iptv.devices.service.LiveDevicesService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.rmi.ServerException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/devices")
public class LiveDevicesController extends BaseController {

    @Resource
    private LiveDevicesService liveDevicesService;

    @Resource
    private RegistrationTokenUtils registrationTokenUtils;
    /**
     * 查询終端设备列表
     */
    @GetMapping("/list")
    public TableDataInfo list(LiveDevices liveDevices)
    {
        startPage();
        List<LiveDevices> list = liveDevicesService.selectDeviceListByView(liveDevices);
        return getDataTable(list);
    }

    /**
     * 获取終端设备详细信息
     */
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId)
    {
        return success(liveDevicesService.selectDeviceByDeviceId(deviceId));
    }

    /**
     * 新增終端设备
     */
    @Log(title = "終端设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LiveDevices liveDevices)
    {
        return toAjax(liveDevicesService.insertDevice(liveDevices));
    }

    /**
     * 修改終端设备
     */
    @Log(title = "終端设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LiveDevices liveDevices)
    {
        return toAjax(liveDevicesService.updateDevice(liveDevices));
    }

    /**
     * 刪除終端设备
     */
    @Log(title = "終端设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds)
    {
        return toAjax(liveDevicesService.deleteDeviceByDeviceIds(deviceIds));
    }

    /**
     * 授权终端设备
     */
    @PostMapping("/updateStatus/{deviceIds}")
    public AjaxResult updateStatus(@PathVariable Long[] deviceIds)
    {
        return toAjax(liveDevicesService.updateStatus(deviceIds));
    }

    /**
     * app点击确认之后后台新增終端设备
     */
    @PostMapping("/externallyAdded")
    public AjaxResult externallyAdded(
            @RequestBody DeviceExternallyAddedDTO dto,
            @RequestHeader(value = "Authorization", required = true) String token) throws ServerException {
        // 校验是否有注册令牌
        AjaxResult tokenCheckResult = registrationTokenUtils.checkToken(token);
        if (tokenCheckResult != null) {
            return tokenCheckResult;
        }

        // 校验设备是否已注册
        int existingDeviceCount = liveDevicesService.checkRegistrationDevice(dto.getMac());
        if (existingDeviceCount != 0) {
            // 如果设备已注册，则校验授权状态
            int status = liveDevicesService.checkStatusByMac(dto.getMac());
            if (status == 1) {
                // 设备未授权，抛出异常
                throw new ServerException("设备未授权");
            }

            // 校验设备是否过期
            LiveDevices device = liveDevicesService.getDeviceByMac(dto.getMac());  // 获取设备信息
            if (device != null && device.getExpirationTime() != null) {
                // 获取设备的过期时间
                Date expirationTime = device.getExpirationTime();
                if (expirationTime.before(new Date())) {
                    // 如果设备过期时间早于当前时间，抛出过期异常
                    throw new ServerException("设备已过期");
                }
            }

            // 设备已授权，且没有过期，返回成功
            return toAjax(existingDeviceCount);
        }

        try {
            // 如果设备未注册，则新增设备
            int success = liveDevicesService.externallyAdded(dto);
            if (success == 0) {
                throw new ServerException("新增设备失败");
            }
            return toAjax(success);  // 返回新增成功的结果
        } catch (Exception e) {
            // 捕获其他异常，返回一个通用错误信息
            throw new ServerException("系统错误，请稍后再试");
        }
    }

    /**
     * 接收mac生成注冊令牌
     * **/
    @GetMapping("/registrationToken/{mac}")
    public AjaxResult registrationToken(@PathVariable String mac) throws ServerException {
        // 初始化LiveDevices对象
        LiveDevices liveDevices = new LiveDevices();
        liveDevices.setMac(mac);

        // 校验MAC是否在redis中存在
        String token = registrationTokenUtils.checkTokenExist(mac);
        if (token != null) {
            // 如果在redis中存在，直接返回
            HashMap<Object, String> map = new HashMap<>();
            map.put("registrationToken", token);
            return AjaxResult.success(map);
        }

        // 如果在redis中不存在，生成新的注册令牌
        String newToken = registrationTokenUtils.getRegistrationToken(mac);
        HashMap<Object, String> map = new HashMap<>();
        map.put("registrationToken", newToken);

        return AjaxResult.success(map);
    }


}
